<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session;
use Crypt;
use Hash;
use DB;
class RegisterController extends Controller
{
    //
    public function register(Request $request)
    {
        if($request -> isMethod('POST'))
        {

            //验证码匹配
       
        $data = $request -> except('_token','repassword');

        $userData['username'] = $data['username'];
        $userData['email'] = $data['email'];
        $userData['phone'] = $data['phone'];
        $userData['password'] = Crypt::encryptString($data['password']);
        $userData['token'] = str_random(50);
        $userData['airline'] = 0;
        $userData['status'] = 0;
        if($request -> hasFile('picname'))
        {
            if($request -> file('picname') -> isValid())
            {
                //处理头像
                // getClientOriginalExtension()    extension()
                $extension = $request -> file('picname') -> getClientOriginalExtension();
                // echo $extension;
                $filename = mt_rand(1000000,9999999).'.'.$extension;
                $dir = './uploads/avatar/';

                $request -> file('picname') -> move($dir,$filename);//storeAs
                $userInfoData['picname'] = '/uploads/avatar/'.$filename;
            }
        }else
        {
            $userInfoData['picname'] = '/uploads/avatar/default.jpg';
        }
        $time = Date('Y-m-d H:i:s');
        $userData['created_at'] = $time;
        $userData['updated_at'] = $time;
    
        //make pic 
        //.....
        //添加数据   //要求用事务处理
        $userId = DB::table('users') -> insertGetId($userData);
        if($userId)
        {
            $userInfoData['uid'] = $userId;
            $userInfoData['created_at'] = $time;
            $userInfoData['updated_at'] = $time;

            $res = DB::table('users_info') -> insert($userInfoData);

            if($res)
            {   
                //store session
                return redirect('/home/login') -> with(['info' => '添加成功']);
            }else
            {
                return back() -> with(['info' => '添加失败']);
            }
        }


        }else{
            return view('home.register.index',['title' => '用户注册']);
        }
        
    }




}
